// Package account_logic_v1
// @Author zhongxc
// @Date 2024/7/30 16:30:00
// @Desc
package account_logic_v1

import (
	"context"
	"net/http"
	"time"
	"vben-api/api/rpc"
	"vben-api/pkg/cache"
	"vben-api/pkg/repository"
	"vben-api/pkg/svc"
	"vben-api/pkg/util"
	userServiceV1 "vben-grpc-common/vben-admin/types/user.service.v1"
)

type AccountLogic struct {
	svcCtx  *svc.ServiceContext
	jwtAuth *util.JwtUtil
	cache   repository.CacheRepo
}

func NewAccountLogic(svcCtx *svc.ServiceContext) *AccountLogic {
	expireAt := time.Duration(svcCtx.Config.JwtConfig.CreatedExpireAt)
	signKey := svcCtx.Config.JwtConfig.SignKey
	refreshSignKey := svcCtx.Config.JwtConfig.RefreshSignKey

	return &AccountLogic{
		svcCtx:  svcCtx,
		cache:   cache.Rc,
		jwtAuth: util.NewJwtUtil(expireAt, signKey, refreshSignKey, cache.Rc),
	}
}

// Login
// @Description: 登录
// @receiver a
// @param in
// @return map[string]any
// @return error
func (a *AccountLogic) Login(username, password string) (map[string]any, error) {
	ctx, cancelFunc := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancelFunc()
	// 参数组装
	in := &userServiceV1.MatchUserPasswordRequest{
		Username: username,
		Password: password,
	}

	// RPC调用远程登录方法
	user, err := rpc.UserServiceClient.MatchUserPassword(ctx, in)
	if err != nil {
		return nil, err
	}

	// 登录成功
	token, err := a.jwtAuth.CreateToken(map[string]any{
		"user_id":  user.Id,
		"username": user.Username,
	})
	if err != nil {
		return nil, err
	}

	err = a.jwtAuth.CreateAuth(user.Id, token)
	if err != nil {
		return nil, err
	}

	result := map[string]any{
		"userId":             user.Id,
		"username":           user.Username,
		"avatar":             user.Avatar,
		"token":              token.AccessToken,
		"refresh_token":      token.RefreshToken,
		"expires_in":         token.AtExpires,
		"refresh_expires_in": token.RtExpires,
	}

	return result, nil
}

// Logout
// @Description: 登出
// @receiver a
// @param req
// @return error
func (a *AccountLogic) Logout(req *http.Request) error {
	// 重置用户信息
	a.svcCtx.ResetUserInfo()

	// 验证token
	token, _ := a.jwtAuth.VerifyToken(req)
	if token == nil {
		return nil
	}

	return nil
}
